# Author: Lovy
# File : 帮派日常任务
# Time : 2023-02-26 15:59
from common.generalFunction import *
import traceback


class BangPairichang():
    @classmethod
    def baidu_ocr(cls, img):
        import requests
        import base64
        headers = {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Accept': 'application/json'
        }
        # access_token 需要修改成自己的
        try:
            with open("baidu_ocr.txt", "r")as file:
                access_token = file.read()
        except Exception as error:
            log.error("{}".format(traceback.format_exc()))
            return {'words_result': []}
        else:
            img_base64 = base64.b64encode(img)
            payload = {"image": img_base64}
            url = "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate?access_token={}".format(access_token)
            response = requests.request("POST", url, headers=headers, data=payload)
            return response.json()

    @classmethod
    def get_index(cls, words, word_list):
        i = 0
        for word in word_list:
            if words in word:
                return i
            i += 1
        return False

    @classmethod
    def get_accurate_index(cls, words, word_list):
        i = 0
        for word in word_list:
            if words == word:
                return i
            i += 1
        return False

    @classmethod
    def click_word(cls, response):
        words_list = []
        words_result = response['words_result']
        if not words_result:
            # 未成功识别 逃跑
            print("未成功识别 诗词 可能是token过期")
            log.info("未成功识别 诗词 可能是token过期")
            return
        for l in words_result:
            words_list.append(l["words"])
        # print(words_list)
        poetry_index = cls.get_index("当前", words_list)
        poetry = words_list[poetry_index][8:13]
        print(poetry)
        log.info(poetry)
        # 找单个的索引
        locs = []
        for w in poetry:
            word_index = cls.get_accurate_index(w, words_list)
            if word_index:
                x = words_result[word_index]["location"]["left"]
                y = words_result[word_index]["location"]["top"]
                locs.append([x, y, x + 15, y - 15])
        print(locs)
        log.info(locs)
        # 点击
        for i in range(len(locs)):
            if loop_Image_until(battle_setting["find_image"]["道具"], times=15):
                battle_use(man_enemy_loc=locs[i], pet_defence=True, auto=False)

    @classmethod
    def bangpairichang_richangpeilian(cls):
        """帮派日常陪练 """
        loop_Image_until(battle_setting["find_image"]["道具"])
        battle_use(pet_skill_name="法攻二阶", man_defence=True, auto=True)
        time.sleep(50)

    @classmethod
    def bangpairichang_redbluegirl(cls):
        """ 红衣、蓝衣仙子 """
        times = 6
        while times > 0:
            if loop_Image_until(battle_setting["find_image"]["道具"], times=10):
                red_girl = loop_Image_until(bangpai_daily["find_image"]["红衣女"], not_all=False, times=20, breakTime=0.1)
                xp.console(red_girl)
                blue_girl = loop_Image_until(bangpai_daily["find_image"]["蓝衣女"], not_all=False, times=20, breakTime=0.1)
                xp.console(blue_girl)
                if (not red_girl) or (not blue_girl):
                    continue
                # red_girl 或 blue_girl 可能为空
                if len(red_girl) > len(blue_girl):
                    if len(blue_girl) == 1:
                        battle_use([blue_girl[0].x, blue_girl[0].y, blue_girl[0].x + 20, blue_girl[0].y + 20],
                                   pet_defence=True)
                    else:
                        battle_use(
                            [blue_girl[0].x, blue_girl[0].y, blue_girl[0].x + 20, blue_girl[0].y + 20],
                            [blue_girl[1].x, blue_girl[1].y, blue_girl[1].x + 20, blue_girl[1].y + 20]
                        )
                else:
                    if len(red_girl) == 1:
                        battle_use([red_girl[0].x, red_girl[0].y, red_girl[0].x + 20, red_girl[0].y + 20],
                                   pet_defence=True)
                    else:
                        battle_use(
                            [red_girl[0].x, red_girl[0].y, red_girl[0].x + 20, red_girl[0].y + 20],
                            [red_girl[1].x, red_girl[1].y, red_girl[1].x + 20, red_girl[1].y + 20]
                        )
                times += 1
            else:
                break
        time.sleep(20)

    @classmethod
    def bangpairichang_tiaozhanshizhe(cls):
        """挑战使者"""
        xp.screenshot("123.png")
        time.sleep(1)
        f = open("123.png", "rb")
        response = cls.baidu_ocr(f.read())
        cls.click_word(response)
        time.sleep(20)

    @classmethod
    def bangpairichang_richangshizhe(cls):
        """
            帮派日常使者  朱雀玄武
            - 识别011 041 051 032 四个位置的值
            - 如果 new_word_loc 前三个word相等 从中 选取一个 平A
            - 否则 前两个相等 直接 平A 021
            - 否则 后三个 选一个平A
        """
        words_loc = {
            "011": [505, 222, 560, 249],
            "041": [234, 391, 290, 418],
            "051": [144, 447, 200, 475],
            "032": [415, 391, 470, 418],
        }
        for i in range(6):
            if loop_Image_until(battle_setting["find_image"]["道具"], times=10):
                new_word_loc = []
                for loc in list(words_loc.keys()):
                    word = ocr(words_loc[loc])
                    new_word_loc.append((word, loc))
                # print(new_word_loc)
                new_word_loc.sort()
                print(new_word_loc)
                log.info(new_word_loc)
                try:
                    if new_word_loc[0][0][0] == new_word_loc[1][0][0]:
                        if new_word_loc[1][0][0] == new_word_loc[2][0][0]:
                            if loop_Image_until(battle_setting["find_image"]["道具"], times=3):
                                battle_use(man_enemy_loc=new_word_loc[0][1], pet_defence=True)
                        else:
                            if loop_Image_until(battle_setting["find_image"]["道具"], times=3):
                                battle_use(man_enemy_loc="021", pet_defence=True)
                    else:
                        if loop_Image_until(battle_setting["find_image"]["道具"], times=3):
                            battle_use(man_enemy_loc=new_word_loc[1][1], pet_defence=True)
                except IndexError:
                    print("索引有误！")
                    battle_use(escape=True)
                    break
            else:
                break
        time.sleep(20)

    @classmethod
    def bangpairichang_caizhenjiakaoguan(cls):
        """猜真假考官"""
        for i in range(5):
            if loop_Image_until(battle_setting["find_image"]["道具"], times=10):
                battle_use(man_enemy_loc="0{}1".format(i + 1), pet_enemy_loc="0{}2".format(i + 1))
            else:
                break  # 等待 任务对话出现
        time.sleep(20)

    @classmethod
    def bangpairichang_lianliankan(cls):
        """连连看"""
        words_loc = {
            "011": [506, 222, 560, 249],
            "031": [325, 335, 380, 362],
            "041": [234, 391, 290, 418],
            "051": [144, 447, 200, 475],
            "032": [415, 391, 470, 418],
        }
        time.sleep(5)
        new_word_loc = []
        for loc in list(words_loc.keys()):
            word = ocr(words_loc[loc])
            # new_loc = [loc[0], loc[1]-75, loc[2], loc[3]-75]
            new_word_loc.append((word, loc))
        # print(new_word_loc)
        new_word_loc.sort()
        print(new_word_loc)
        log.info(new_word_loc)
        """'乌龙', '炎龙', '青龙'"""
        """l = [0,1,2,3,4] l[0]=l[1] 点击 否则 点击 l[0] 点击 021"""
        # 第一个回合
        if new_word_loc[0][0][0] == new_word_loc[1][0][0]:
            if loop_Image_until(battle_setting["find_image"]["道具"], times=10):
                battle_use(man_enemy_loc=new_word_loc[0][1], pet_enemy_loc=new_word_loc[1][1])
                # 第二个回合
                if new_word_loc[2][0][0] == new_word_loc[3][0][0]:
                    if loop_Image_until(battle_setting["find_image"]["道具"], times=10):
                        battle_use(man_enemy_loc=new_word_loc[2][1], pet_enemy_loc=new_word_loc[3][1])
                    # 第三个回合
                    if loop_Image_until(battle_setting["find_image"]["道具"], times=10):
                        battle_use(man_enemy_loc=new_word_loc[4][1], pet_enemy_loc="021")
                # 第三个回合
                else:
                    if loop_Image_until(battle_setting["find_image"]["道具"], times=10):
                        battle_use(man_enemy_loc=new_word_loc[2][1], pet_enemy_loc="021")
        else:
            if loop_Image_until(battle_setting["find_image"]["道具"], times=10):
                battle_use(man_enemy_loc=new_word_loc[0][1], pet_enemy_loc="021")
            # 第二个回合
            if new_word_loc[1][0][0] == new_word_loc[2][0][0]:
                if loop_Image_until(battle_setting["find_image"]["道具"], times=10):
                    battle_use(man_enemy_loc=new_word_loc[2][1], pet_enemy_loc=new_word_loc[1][1])
                # 第三个回合
                if loop_Image_until(battle_setting["find_image"]["道具"], times=10):
                    battle_use(man_enemy_loc=new_word_loc[3][1], pet_enemy_loc=new_word_loc[4][1])
            else:
                print("识别有误！")
                log.info("识别有误！")
                battle_use(escape=True)
                time.sleep(10)


    @classmethod
    def handle_man_bangpai(cls):
        if loop_Image_until(battle_setting["find_image"]["道具"], times=10):
            res = xp.findText("日常陪练", 3, 117, 667, 664)
            if res:
                print("日常陪练: {}".format(res))
                log.info("日常陪练: {}".format(res))
                cls.bangpairichang_richangpeilian()
                return
            res = xp.findText("考官", 3, 117, 667, 664)
            if res:
                print("真假考官: {}".format(res))
                log.info("真假考官: {}".format(res))
                cls.bangpairichang_caizhenjiakaoguan()
                return
            res = xp.findText("仙子", 3, 117, 667, 664)
            if res:
                print("红蓝仙子: {}".format(res))
                log.info("红蓝仙子: {}".format(res))
                cls.bangpairichang_redbluegirl()
                return
            res = xp.findText("日常使者", 3, 117, 667, 664)
            if res:
                print("朱雀 玄武: {}".format(res))
                log.info("朱雀 玄武: {}".format(res))
                cls.bangpairichang_richangshizhe()
                return
            res = xp.findText("连连看", 3, 117, 667, 664)
            if res:
                print("连连看: {}".format(res))
                log.info("连连看: {}".format(res))
                cls.bangpairichang_lianliankan()
                return
            res = xp.findText("挑战使者", 3, 117, 667, 664)
            if res:
                """执行前 确认 左下角 信息框 箭头朝上"""
                print("挑战使者: {}".format(res))
                log.info("挑战使者: {}".format(res))
                cls.bangpairichang_tiaozhanshizhe()
            print("执行完一轮。。。")
            log.info("执行完一轮。。。")

    @classmethod
    def exec_script(cls):
        times = 5
        while times > 0:
            # todo 如果 10次 都没有过一个任务 就停止整个任务
            exec_times = 0
            if loop_until(task_fuben["find_color"], "人物对话叉号", times=20):
                first_button = ocr(mainUI["对话"]["first_button"])
                click(mainUI["对话"]["first_button"], text="{}".format(first_button))
                if "继续" in first_button:
                    times -= 1
                    # 如果五次挑战都失败 就结束当前任务
                    exec_times += 1
                    if exec_times == 10:
                        break
                # 离开 即 退出
                elif "开" in first_button:
                    break
                cls.handle_man_bangpai()
        time.sleep(10)


# 帮派日常任务
def goto_bangpairichang(vip=True):
    if vip:
        # 循环找图 帮派总管
        res = loop_until(main_task["find_color"], "人物对话叉号", times=20)
        if res:
            person_name = ocr(main_task["对话"]["name_loc"])
            xp.console("帮派总管检测:", person_name)
            log.info("帮派总管检测:{}".format(person_name))
            if person_name:
                click(main_task["对话"]["first_button"], text="点击 速通")
            time.sleep(5)
    else:
        res = loop_until(main_task["find_color"], "人物对话叉号", times=20)
        if res:
            person_name = ocr(main_task["对话"]["name_loc"])
            xp.console("帮派总管检测:", person_name)
            log.info("帮派总管检测:{}".format(person_name))
            if person_name:
                click(main_task["对话"]["first_button"], text="点击 帮派日常")
                BangPairichang.exec_script()
                if loop_until(task_fuben["find_color"], "人物对话叉号", times=20):
                    click(main_task["对话"]["叉号"], text="点击 叉号")
            time.sleep(5)
